import os
import shutil
import time

import pytest

from Logs.log_handle import get_log

log = get_log(os.path.basename(__file__))


def main(case_key):
    """
    执行测试并生成 Allure 历史趋势报告
    :param case_key: Redis 用例 key
    """
    case_dir = os.path.dirname(os.path.abspath(__file__))
    test_case_path = os.path.join(case_dir, "test_case.py")

    timestamp = time.strftime("%Y-%m-%d_%H-%M-%S")
    allure_results_dir = os.path.join(case_dir, "allure_file", f"allure-results-{timestamp}")
    allure_history_dir = os.path.join(case_dir, "allure_file", "allure-history")

    os.makedirs(allure_results_dir, exist_ok=True)
    os.makedirs(allure_history_dir, exist_ok=True)

    # 运行 pytest，开启重试机制
    exit_code = pytest.main([
        "-q",
        "-n", "auto",
        test_case_path,
        f"--case-key={case_key}",
        # "--reruns", "3",  # 失败重试 3 次
        f"--alluredir={allure_results_dir}"
    ])

    if exit_code != 0:
        log.error("测试执行失败，请检查日志！")
        return None

    log.info("测试执行成功！")

    # 生成历史趋势报告（allure-history）
    report_backup_dir = os.path.join(allure_history_dir, f"{timestamp}")
    os.makedirs(report_backup_dir, exist_ok=True)

    shutil.copytree(allure_results_dir, os.path.join(report_backup_dir, "results"), dirs_exist_ok=True)
    os.system(f"allure generate {allure_results_dir} -o {report_backup_dir} --clean")

    return {
        "individual_report": os.path.join(report_backup_dir, "index.html")
    }


if __name__ == "__main__":
    result = main("18cdbd1d-1775-4114-a76e-2ed006112b4d,528f27d6-8831-496c-9659-b58590ffbbb7,528f27d6-8831-496c-9659-b58590ffbbbs")
    if result:
        log.info(f"独立报告路径: {result['individual_report']}")
    else:
        log.error("测试未成功执行。")